package cn.jit.ssm.service.impl;

import cn.jit.ssm.beans.domain.Book;
import cn.jit.ssm.beans.entity.JitBook;
import cn.jit.ssm.beans.entity.JitBookExample;
import cn.jit.ssm.mapper.JitBookMapper;
import cn.jit.ssm.service.JitBookService;
import cn.jit.ssm.support.JSONReturn;
import cn.jit.ssm.utils.ExcelUtil;
import cn.jit.ssm.utils.HttpClientUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: Cecurio
 * @create: 2017-12-13 16:28
 **/
@Service
public class JitBookServiceImpl implements JitBookService {
    final Logger logger = LoggerFactory.getLogger(JitBookServiceImpl.class);

    @Autowired
    private JitBookMapper jitBookMapper;

    @Override
    public JSONReturn insertSelective(String isbn) {
        Book book = HttpClientUtil.doGet("https://api.douban.com/v2/book/isbn/" + isbn, Book.class);
        JitBook record = new JitBook();
        record.setTitle(book.getTitle());
        record.setImage(book.getImage());
        record.setIsbn13(book.getIsbn13());
        String price = book.getPrice();
        record.setPrice(Double.parseDouble(book.getPrice().substring(0, price.length() - 1)));
        record.setUrl(book.getUrl());
        record.setSummary(book.getSummary());

        // 判断书籍是否在自己的数据库中
        JitBookExample jitBookExample = new JitBookExample();
        jitBookExample.or().andIsbn13EqualTo(book.getIsbn13());
        List<JitBook> jitBooks = jitBookMapper.selectByExample(jitBookExample);
        if (jitBooks != null && jitBooks.size() != 0) {
            return JSONReturn.buildFailure("此书已经在您的数据库中");
        }

        int num = jitBookMapper.insertSelective(record);
        if (num > 0) {
            return JSONReturn.buildSuccess("插入成功");
        }
        return JSONReturn.buildFailure("插入失败");
    }

    @Override
    public JSONReturn getAllBooks() {

        List<JitBook> jitBooks = jitBookMapper.selectByExample(new JitBookExample());

        System.out.println("======");
        for (JitBook item : jitBooks) {
            System.out.println(item.getTitle());
        }
        System.out.println("======");

        if (jitBooks == null || jitBooks.size() == 0) {
            return JSONReturn.buildFailure("查询失败！");
        }
        return JSONReturn.buildSuccess(jitBooks);
    }

    @Override
    public JSONReturn getBooks(String pageNum, String pageSize) {
        //分页处理
        Map<String, Object> map = null;
        try {
            PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
            List<JitBook> jitBooks = jitBookMapper.selectByExample(new JitBookExample());
            System.out.println("======");
            for (JitBook item : jitBooks) {
                System.out.println(item.getTitle());
            }
            System.out.println("======");
            PageInfo<JitBook> pageInfo = new PageInfo<JitBook>(jitBooks);
            long total = pageInfo.getTotal(); //获取总记录数
            System.out.println("获取总记录数: " + total);
            if (jitBooks == null || jitBooks.size() == 0) {
                return JSONReturn.buildFailure("查询失败！");
            }
            map = new ConcurrentHashMap<String, Object>();
            map.put("totalCount", total);
            map.put("data", jitBooks);
        } catch (Exception e) {
            return JSONReturn.buildFailure("查询失败，传参异常！");
        }

        return JSONReturn.buildSuccess(map);
    }

    @Override
    public String getBooKByDataTable(int pageNum, int iDisplayLength) {
        logger.info("使用pageHelper和datatable分页获取图书开始");

        JSONObject getObj = new JSONObject();
        try {
            PageHelper.startPage(pageNum, iDisplayLength);
            List<JitBook> jitBooks = jitBookMapper.selectByExample(new JitBookExample());
            logger.info("此次获取的书籍有: " + jitBooks.toString());
            PageInfo<JitBook> pageInfo = new PageInfo<JitBook>(jitBooks);

            //获取总记录数
            long total = pageInfo.getTotal();
            logger.info("获取总记录数: " + total);

            if (jitBooks.size() == 0) {
                getObj.put("success", false);
                return getObj.toString();
            }

            getObj.put("iTotalRecords", total);          //实际的行数
            getObj.put("iTotalDisplayRecords", total);   //显示的行数,这个要和上面写的一样
            getObj.put("aaData", jitBooks);//要以JSON格式返回，否则前台没法显示
        } catch (Exception e) {
            getObj.put("success", false);
            return getObj.toString();
        }
        return getObj.toString();
    }

    @Override
    public void exportBookToExcel(HttpServletResponse response) {
        String[] titles = new String[]{"bookId", "title", "image", "price", "url", "isbn13", "summary"};
        List<JitBook> jitBooks = jitBookMapper.selectByExample(new JitBookExample());
        List<Object[]> tableData = new ArrayList<>();
        JitBook tempBook = null;
        for (int i = 0; i < jitBooks.size(); i++) {
            tempBook = jitBooks.get(i);
            String[] temps = new String[]{tempBook.getBookId().toString(), tempBook.getTitle(), tempBook.getImage(),
                tempBook.getPrice().toString(), tempBook.getUrl(), tempBook.getIsbn13(), "由于部分summary太大，超出255字符，故不导出！"};
            tableData.add(temps);
        }

        ExcelUtil.exportXlsExcel(response, titles, "douban_programming_books", tableData);
    }
}
